import axios from "axios";
import transform from "../utils/transform";

export default {
  data() {
    return {
      title: ""
    };
  },
  props: ["dialogVisible", "opId"],
  methods: {
    addFunc() {
      return axios.post(this.addUrl, transform(this.postData));
    },
    editFunc() {
      return axios.patch(
        this.editUrl || this.addUrl,
        transform({
          ...this.postData,
          id: this.opId
        })
      );
    },
    cancel() {
      this.$emit("cancel");
    },
    async handleOpen() {
      if (this.opId) {
        this.title = "更新";
        const {
          data: { errno, message, data }
        } = await axios.get(
          (this.getDetailUrl || this.addUrl) + "/" + this.opId
        );
        if (!errno) {
          for (const key in this.postData) {
            if (data[key]) this.postData[key] = data[key];
            if (typeof data[key] === "boolean") this.postData[key] = +data[key];
          }
        } else {
          this.$message({ type: "error", message });
        }
      } else {
        this.title = "新增";
      }
    },
    handleClose() {
      this.$refs.postForm && this.$refs.postForm.resetFields();
      for (const key in this.postData) {
        if (this.postData) {
          this.postData[key] = "";
        }
      }
      this.cancel();
    },
    submitFunc() {
      if (this.opId && !this.isAdd) {
        return this.editFunc();
      } else {
        return this.addFunc();
      }
    },
    async submit() {
      this.$refs.postForm.validate(async valid => {
        if (valid) {
          const {
            data: { errno, message }
          } = await this.submitFunc();
          if (!errno) {
            this.$message({ type: "success", message: this.title + "成功" });
            this.$emit("cancel");
          } else {
            this.$message({ type: "error", message });
          }
        }
      });
    }
  }
};
